﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Drawing;
using System.Drawing.Design;
using System.Drawing.Drawing2D;
using System.Drawing.Printing;
using System.Drawing.Imaging;
using System.IO;

public partial class _Image : System.Web.UI.Page
{
    //验证码名称 Session["CheckCode"]
    private string CreateCheckCodeString()
    { //定义用于验证码的字符数组
        char[] AllCheckCodeArray ={ '2','3','4','5','6','7','8','9','a','b','c','d','e','f','g','h','i','j','k','m','n','p','q',
        'r','s','t','u','v','w','x','y','z'};
        //定义验证码字符串
        string randomcode = "";
        Random rd = new Random();
        //生成4位验证码字符串
        for (int i = 0; i < 4; i++)
            randomcode += AllCheckCodeArray[rd.Next(AllCheckCodeArray.Length)];
        return randomcode;
    }
    Random ran = new Random();
    protected void Page_Load(object sender, EventArgs e)
    {
        string str = CreateCheckCodeString();
        Session["CheckCode"] = str;
        getImageValidate(str);

    }
    private void getImageValidate(string strValue)
    {
        Bitmap img = new Bitmap(80, 38);
        Graphics gfc = Graphics.FromImage(img);
        gfc.Clear(Color.White);
        drawLine(gfc, img);
        Font font = new Font("宋体", 20, FontStyle.Bold);
        System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, img.Width, img.Height), Color.Gray, Color.Black, 1.5f, true);
        gfc.DrawString(strValue, font, brush, 3, 2);
        drawPoint(img);
        gfc.DrawRectangle(new Pen(Color.Gray), 0, 0, img.Width - 1, img.Height - 1);
        MemoryStream ms = new MemoryStream();
        img.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
        Response.ClearContent();
        Response.ContentType = "image/gif";
        Response.BinaryWrite(ms.ToArray());
        gfc.Dispose();
        img.Dispose();
        Response.End();
    }
    private void drawLine(Graphics gfc, Bitmap img)
    {
        for (int i = 0; i < 10; i++)
        {
            int x1 = ran.Next(img.Width);
            int y1 = ran.Next(img.Height);
            int x2 = ran.Next(img.Width);
            int y2 = ran.Next(img.Height);
            gfc.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
        }
    }
    private void drawPoint(Bitmap img)
    {
        int col = ran.Next();
        for (int i = 0; i < 100; i++)
        {
            int x = ran.Next(img.Width);
            int y = ran.Next(img.Height);
            img.SetPixel(x, y, Color.Black);
        }
    }
}
